package com.w3c.pragmatic.config;

import com.w3c.pragmatic.utils.SnowflakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * ...
 *
 * @author wangdong
 * @since 2025/3/12 13:47
 */
@Slf4j
@Configuration
public class SnowflakeConfig {

  // 创建雪花算法工具bean
  @Bean
  public SnowflakeUtil propertyConfigurer() {
    Long workId = getWorkId();
    Long dataCenterId = getDataCenterId();
    log.info("SnowflakeConfig#当前机器workId={}, dataCenterId={}", workId, dataCenterId);
    return new SnowflakeUtil(workId, dataCenterId);
  }

  /**
   * workId使用IP生成
   *
   * @return workId
   */
  private static Long getWorkId() {
    try {
      String hostAddress = Inet4Address.getLocalHost().getHostAddress();
      log.info("SnowflakeConfig#当前机器ip地址={}", hostAddress);
      // 将字符串转换为Unicode代码点数组
      int[] ints = StringUtils.toCodePoints(hostAddress);
      int sums = 0;
      for (int b : ints) sums = sums + b;
      return (long) (sums % 32);
    } catch (UnknownHostException e) {
      // 失败就随机
      return RandomUtils.nextLong(0, 31);
    }
  }

  /**
   * dataCenterId使用hostName生成
   *
   * @return dataCenterId
   */
  private static Long getDataCenterId() {
    try {
      String hostName = SystemUtils.getHostName();
      log.info("SnowflakeConfig#当前机器hostName={}", hostName);
      // 将字符串转换为Unicode代码点数组
      int[] ints = StringUtils.toCodePoints(hostName);
      int sums = 0;
      for (int i : ints) sums = sums + i;
      return (long) (sums % 32);
    } catch (Exception e) {
      // 失败就随机
      return RandomUtils.nextLong(0, 31);
    }
  }
}
